package cn.zhz.springdoc.springboot.service.impl;

import cn.hutool.json.JSONUtil;
import cn.zhz.springdoc.core.dto.ApiPushDto;
import cn.zhz.springdoc.core.enums.OpenApiParserEnum;
import cn.zhz.springdoc.springboot.property.OpenApiProperty;
import cn.zhz.springdoc.springboot.service.IOpenApiParser;
import cn.zhz.springdoc.springboot.util.PropertyUtil;
import io.swagger.models.Swagger;
import lombok.RequiredArgsConstructor;
import springfox.documentation.service.Documentation;
import springfox.documentation.spring.web.DocumentationCache;
import springfox.documentation.swagger2.mappers.ServiceModelToSwagger2Mapper;

/**
 * @author ZHZ
 * @since 2022-11-18
 */
@RequiredArgsConstructor
public class OpenApi2ParserImpl implements IOpenApiParser {

    private final ServiceModelToSwagger2Mapper mapper;

    private final DocumentationCache documentationCache;

    private final OpenApiProperty openApiProperty;

    /**
     * 解析器名称
     *
     * @return
     */
    @Override
    public OpenApiParserEnum name() {
        return OpenApiParserEnum.API_2;
    }

    /**
     * 解析
     *
     * @return
     */
    @Override
    public ApiPushDto parser() {

        Swagger swagger = null;
        if (this.mapper != null && this.documentationCache != null) {
            Documentation documentation = this.documentationCache.documentationByGroup(openApiProperty.getGroupName());
            if (documentation != null) {
                swagger = this.mapper.mapDocumentation(documentation);

                String hostAddress = PropertyUtil.getHost();
                String port = PropertyUtil.getPort();
                swagger.setHost(hostAddress + ":" + port);
                swagger.setBasePath(PropertyUtil.getContextPath());
                swagger.getInfo().setTermsOfService("http://" + hostAddress + ":" + port);
            }
        }

        return new ApiPushDto(this.name().getCode(), openApiProperty.getProjectName(), openApiProperty.getGroupName(), JSONUtil.toJsonStr(swagger));

    }
}
